Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

229
Visualizações
How to have a function tell whether to apply on "this" or other element ID

I have a function like this:

function toggle(me, style) {
  var myelm = me == '' ? this : document.getElementById(me);
 
  myelm.classList = style; 
}

I want the function to know when it has to apply the style to the triggering element or to some other element like in the following examples:

 <div onclick="toggle(this);"></div> <!--this function should apply to this element only-->
 <div onclick="toggle('otherelement');"></div> <!--this should apply to other element of the DOM-->

but it only works when the ID is specified, and wont apply on this as intended. What is wrong?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the first case you pass a DOM element, in the second a (non-empty) string. So the condition me == '' that you check is not true in either case. Secondly, this is irrelevant in the function, since you never call it with a this binding (a this binding is not the same thing as passing this as argument).

You'll want to check the data type of the argument, and when it is a string, retrieve the DOM element, and otherwise just use the argument that was given (me) -- not this:

Another thing: you need to call the toggle method on the classList property:

function toggle(me, style) {
  var myelm = typeof me != 'string' ? me : document.getElementById(me);
 
  myelm.classList.toggle(style);
}

NB: make sure to also pass the second argument (style)!

Snippet:

function toggle(me, style) {
  var myelm = typeof me != 'string' ? me : document.getElementById(me);
 
  myelm.classList.toggle(style);
}
.highlight { background: yellow }
<div id="otherelement">This is other element</div>

<p></p>

<div onclick="toggle(this, 'highlight');">toggle this</div>
<div onclick="toggle('otherelement', 'highlight');">toggle other element</div>  
 

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda